package provisioner.algorithm;

import java.util.*;

import jp.aist.gtrc.plus.scheduler.node.NodeInfo;

public class IdleNodeTracker {
    public static final int MAX_IDLE_TIME = 60; // seconds

    private Map<String,Long> idleTimeMap;
    private long lastTime;
 
    public IdleNodeTracker() {
       idleTimeMap = new HashMap<String,Long>();
       lastTime = Long.MAX_VALUE;
    }

    public Collection<NodeInfo> filter(Collection<NodeInfo> unusedNodes) {
       long now = System.currentTimeMillis();
       long elasped = System.currentTimeMillis() - lastTime;

       Map<String,NodeInfo> nodeMap = new HashMap<String,NodeInfo>();
       Map<String,Long> tempTimeMap = new HashMap<String,Long>();
       if (unusedNodes != null) {
          for (NodeInfo node : unusedNodes) {
             Long idleTime = idleTimeMap.get(node.getName());
             if ( (elasped < 0) || (idleTime == null) ) {
                tempTimeMap.put(node.getName(),new Long(0));
             } else {
                tempTimeMap.put(node.getName(),idleTime + elasped);
                nodeMap.put(node.getName(),node);
             }
          }
       }
       idleTimeMap = tempTimeMap;

       Collection<NodeInfo> expiredNodes = new ArrayList<NodeInfo>();
       for (String nodeName : idleTimeMap.keySet()) {
          int t = (int) (idleTimeMap.get(nodeName)/1000);  
          if (t > MAX_IDLE_TIME) {
             System.out.println("Node " + nodeName + " time " + t + " expired");
             expiredNodes.add(nodeMap.get(nodeName)); 
          }
       }
       lastTime = now;

/*
       System.out.print("Unused nodes ");
       for (String nodeName: idleTimeMap.keySet()) {
          System.out.print(nodeName + ":" + (idleTimeMap.get(nodeName)/1000) + ",");
       }
       System.out.println(); 
*/

       return expiredNodes;
    }

}

